/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.util;

/**
 *
 * @author Jerry
 */
import java.io.*;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

public class FileUpload {

    private static final int BUFFER_SIZE = 6124;

    public void handleFileUpload(FileUploadEvent event) {
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        String p = extContext.getRealPath(event.getFile().getFileName());
        String[] temp = p.split("build");//gfdeploy//Demo_Primefaces_JSF_Part2//Demo_Primefaces_JSF_Part2-war_war");
        p = temp[0] + "web//resources//Images//imageAdmin//";
        File result = new File(p + event.getFile().getFileName());
        //"D:\APT\SEM 4\SV\babyshop-primefaces\Demo_Primefaces_JSF_Part2\Jellyfish.jpg"
        System.out.println(p);
        try {

            FileOutputStream fileOutputStream = new FileOutputStream(result);

            byte[] buffer = new byte[BUFFER_SIZE];
            int bulk;
            InputStream inputStream = event.getFile().getInputstream();
            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();

            }
            fileOutputStream.close();
            inputStream.close();

            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName()
                    + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (IOException e) {
            e.printStackTrace();
            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
}
